// src/utils/user-agent.util.ts
import * as Bowser from "bowser";

/**
 * 用户代理解析结果
 */
export interface ParsedUserAgent {
    browser: {
        name: string;
        version: string;
        majorVersion: number;
    };
    os: {
        name: string;
        version: string;
        versionName: string;
    };
    platform: {
        type: "desktop" | "mobile" | "tablet" | "unknown";
    };
    engine: {
        name: string;
    };
    isMobile: boolean;
    isTablet: boolean;
    isDesktop: boolean;
    isBot: boolean;
    userAgentString: string;
}

/**
 * 用户代理工具类
 */
export class UserAgentUtils {
    private static botPatterns = [
        /bot/i,
        /crawl/i,
        /spider/i,
        /slurp/i,
        /search/i,
        /facebook/i,
        /twitter/i,
        /whatsapp/i,
        /linkedin/i,
        /google/i,
        /bing/i,
        /yahoo/i
    ];

    /**
     * 解析 User-Agent 字符串
     */
    static parse(userAgent: string): ParsedUserAgent {
        if (!userAgent) {
            return this.createEmptyResult();
        }

        try {
            const parser = Bowser.getParser(userAgent);
            const result = parser.getResult();
            const majorVersion = this.extractMajorVersion(result.browser.version);

            return {
                browser: {
                    name: result.browser.name || "unknown",
                    version: result.browser.version || "unknown",
                    majorVersion
                },
                os: {
                    name: result.os.name || "unknown",
                    version: result.os.version || "unknown",
                    versionName: result.os?.versionName || "unknown"
                },
                platform: {
                    type: (result.platform.type as any) || "unknown"
                },
                engine: {
                    name: result.engine.name || "unknown"
                },
                isMobile: result.platform.type === "mobile",
                isTablet: result.platform.type === "tablet",
                isDesktop: result.platform.type === "desktop",
                isBot: this.detectBot(userAgent),
                userAgentString: userAgent
            };
        } catch (error) {
            console.warn("User-Agent parsing failed:", error);
            return this.createEmptyResult();
        }
    }

    /**
     * 检查是否满足特定浏览器版本要求
     * @example
     * UserAgentUtils.satisfies(userAgent, { chrome: '>=80', firefox: '>78' })
     */
    static satisfies(userAgent: string, conditions: Record<string, string>): boolean {
        if (!userAgent) return false;

        try {
            const parser = Bowser.getParser(userAgent);
            return parser.satisfies(conditions);
        } catch (error) {
            console.warn("Browser version check failed:", error);
            return false;
        }
    }

    /**
     * 检查是否为特定浏览器
     */
    static isBrowser(userAgent: string, browserName: string): boolean {
        return this.parse(userAgent).browser.name.toLowerCase() === browserName.toLowerCase();
    }

    /**
     * 检查是否为特定操作系统
     */
    static isOS(userAgent: string, osName: string): boolean {
        return this.parse(userAgent).os.name.toLowerCase() === osName.toLowerCase();
    }

    /**
     * 检查是否为特定平台类型
     */
    static isPlatform(userAgent: string, platformType: "mobile" | "tablet" | "desktop"): boolean {
        return this.parse(userAgent).platform.type === platformType;
    }

    /**
     * 检测是否为爬虫/机器人
     */
    private static detectBot(userAgent: string): boolean {
        return this.botPatterns.some(pattern => pattern.test(userAgent));
    }

    /**
     * 提取主要版本号（如 120.0.0.0 -> 120）
     */
    private static extractMajorVersion(version: string): number {
        if (!version) return 0;
        const match = version.match(/^(\d+)/);
        return match ? parseInt(match[1], 10) : 0;
    }

    /**
     * 创建空结果对象
     */
    private static createEmptyResult(): ParsedUserAgent {
        return {
            browser: {
                name: "unknown",
                version: "unknown",
                majorVersion: 0
            },
            os: {
                name: "unknown",
                version: "unknown",
                versionName: "unknown"
            },
            platform: {
                type: "unknown"
            },
            engine: {
                name: "unknown"
            },
            isMobile: false,
            isTablet: false,
            isDesktop: false,
            isBot: false,
            userAgentString: ""
        };
    }
}

// test-user-agents.ts
// export const TEST_USER_AGENTS = {
//     // 桌面浏览器
//     desktop: {
//         chromeWindows:
//             "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
//         chromeMac:
//             "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
//         firefoxWindows: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0",
//         firefoxMac: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:121.0) Gecko/20100101 Firefox/121.0",
//         safariMac:
//             "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",
//         edgeWindows:
//             "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
//         ie11: "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
//     },

//     // 移动设备
//     mobile: {
//         iphoneSafari:
//             "Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1",
//         iphoneChrome:
//             "Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/120.0.6099.119 Mobile/15E148 Safari/604.1",
//         androidChrome:
//             "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.144 Mobile Safari/537.36",
//         samsungInternet:
//             "Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/23.0 Chrome/115.0.5790.166 Mobile Safari/537.36",
//         huaweiBrowser:
//             "Mozilla/5.0 (Linux; Android 13; VOG-L29) AppleWebKit/537.36 (KHTML, like Gecko) HuaweiBrowser/13.0.3.300 Mobile Safari/537.36"
//     },

//     // 平板设备
//     tablet: {
//         ipadSafari:
//             "Mozilla/5.0 (iPad; CPU OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1",
//         ipadChrome:
//             "Mozilla/5.0 (iPad; CPU OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/120.0.6099.119 Mobile/15E148 Safari/604.1",
//         androidTablet:
//             "Mozilla/5.0 (Linux; Android 13; SM-X700) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.144 Safari/537.36"
//     },

//     // 爬虫/机器人
//     bots: {
//         googlebotDesktop: "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
//         googlebotMobile:
//             "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.110 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
//         bingbot: "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
//         facebookBot: "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",
//         twitterBot: "Twitterbot/1.0",
//         whatsappBot: "WhatsApp/2.23.24.81 iOS/17.2 Device/iPhone"
//     },

//     // 特殊情况
//     edgeCases: {
//         empty: "",
//         unknown: "Unknown User Agent",
//         legacy: "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
//     }
// };

// // 导出为数组格式，方便循环测试
// export const ALL_TEST_UAS = [
//     ...Object.values(TEST_USER_AGENTS.desktop),
//     ...Object.values(TEST_USER_AGENTS.mobile),
//     ...Object.values(TEST_USER_AGENTS.tablet),
//     ...Object.values(TEST_USER_AGENTS.bots),
//     ...Object.values(TEST_USER_AGENTS.edgeCases)
// ];

// // 按类型分组的测试函数
// export const testGroups = {
//     desktop: Object.values(TEST_USER_AGENTS.desktop),
//     mobile: Object.values(TEST_USER_AGENTS.mobile),
//     tablet: Object.values(TEST_USER_AGENTS.tablet),
//     bots: Object.values(TEST_USER_AGENTS.bots),
//     all: ALL_TEST_UAS
// };

// // 测试你的 UserAgentUtils

// // 测试桌面浏览器
// console.log("=== 桌面浏览器测试 ===");
// Object.entries(TEST_USER_AGENTS.desktop).forEach(([name, ua]) => {
//     const result = UserAgentUtils.parse(ua);
//     console.log(`${name}: ${result.browser.name} ${result.os.name} - ${result.platform.type}`);
// });

// // 测试移动端
// console.log("\n=== 移动端测试 ===");
// Object.entries(TEST_USER_AGENTS.mobile).forEach(([name, ua]) => {
//     const result = UserAgentUtils.parse(ua);
//     console.log(`${name}: ${result.isMobile ? "✅ Mobile" : "❌ Not Mobile"}`);
//     console.log(`${name}: ${result.browser.name} ${result.os.name} - ${result.platform.type}`);
// });

// // 测试爬虫检测
// console.log("\n=== 爬虫检测测试 ===");
// Object.entries(TEST_USER_AGENTS.bots).forEach(([name, ua]) => {
//     const result = UserAgentUtils.parse(ua);
//     console.log(`${name}: ${result.isBot ? "✅ Bot detected" : "❌ Not detected as bot"}`);
//     console.log(`${name}: ${result.browser.name} ${result.os.name} - ${result.platform.type}`);
// });

// // 测试版本检查
// console.log("\n=== 版本检查测试 ===");
// const chromeUA = TEST_USER_AGENTS.desktop.chromeWindows;
// const isModern = UserAgentUtils.satisfies(chromeUA, { chrome: ">=100" });
// console.log(`Chrome 120 >= 100: ${isModern ? "✅" : "❌"}`);
